package com.hmdp.utils;



import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class SimpleRedisLock implements ILock{

    private final  String name;
    private static final String KEY_PREFIX = "lock:";
    private final StringRedisTemplate stringRedisTemplate;
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation( new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    @Override
    public boolean tryLock(long timeoutSec) {
        String id =ID_PREFIX+ Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(name + KEY_PREFIX, id , timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);
    }
    public void unLock() {
        //调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(name + KEY_PREFIX),
                ID_PREFIX+ Thread.currentThread().getId()
        );
    }
   /* @Override
    public void unLock() {
        String id = ID_PREFIX+ Thread.currentThread().getId();
        String id1 = stringRedisTemplate.opsForValue().get(name + KEY_PREFIX);
        if (id.equals(id1)){
            stringRedisTemplate.delete(name + KEY_PREFIX);
        }
    }*/
}
